<?php

namespace apps\marriage\core\service;

use apps\marriage\core\logic\FileLogic;
use apps\marriage\core\model\VipCard;
use think\Exception;
use think\facade\Validate;
use vm\com\BaseService;

class VipCardService extends BaseService
{
    /**
     * @return VipCard
     */
    protected function getModel()
    {
        return new VipCard();
    }

    /**
     * @var Validate
     */
    private $validate;

    protected function init()
    {
        parent::init();
        $this->validate = Validate::rule([
            'name' => 'require',
            'vip_level' => function($value) {
                if(is_numeric($value) && intval($value) > 0) {
                    return true;
                }
                return false;
            },
            'expire_days' => function($value) {
                if(is_numeric($value) && intval($value) > 0) {
                    return true;
                }
                return false;
            },
            'end_active_time' => function($value) {
                if(is_numeric($value) && intval($value) > 0) {
                    return true;
                }
                return false;
            },
        ]);
    }

    /**
     * @return VipCardNoService
     */
    private function getVipCardNoService()
    {
        return service('VipCardNo', SERVICE_NAMESPACE);
    }

    /**
     * @return FileLogic
     */
    private function getFileLogic()
    {
        return logic('File', LOGIC_NAMESPACE);
    }

    public function save(array $data)
    {
        if(!$this->validate->check($data)) {
            throw new Exception($this->validate->getError());
        }
        $data['end_active_time'] = strtotime(date('Ymd 23:59:59', $data['end_active_time']));

        if($data['id'] == 0) {
            $cardId = $this->create($data);
            $this->getVipCardNoService()->onGenerate($cardId, 100);
            return $cardId;
        } else {
            return $this->updateByPk($data);
        }
    }

    public function format(array $data)
    {
        $site = config('site');
        $vipLevels = $site['vip_levels'];
        $data['vip'] = isset($vipLevels[$data['vip_level']]) ? $vipLevels[$data['vip_level']] : null;

        if($data['frontend_image'] > 0) {
            $image = $this->getFileLogic()->file($data['frontend_image']);
            $data['frontend_image_url'] = $image['url'];
        } else {
            $data['frontend_image_url'] = '';
        }

        if($data['backend_image'] > 0) {
            $image = $this->getFileLogic()->file($data['backend_image']);
            $data['backend_image_url'] = $image['url'];
        } else {
            $data['backend_image_url'] = '';
        }

        return $data;
    }
}